package com.lwt.codetop.linkedLists;

// 148. 排序链表

import java.lang.management.LockInfo;
import java.util.List;

/**
 * 思路：链表的归并排序
 *      1. 获取中间节点，将链表划分为两段
 *      2. 递归排序左右两段
 *      3. 归并两个有序链表
 */
public class SortList {
    public static void main(String[] args) {
        // 构建测试用例
        ListNode head = new ListNode(4);
        head.next = new ListNode(2);
        head.next.next = new ListNode(1);
        head.next.next.next = new ListNode(3);

        // 排序链表
        ListNode res = sortList(head);
        while (res != null){
            System.out.print(res.val + " ");
            res = res.next;
        }
    }

    /**
     * 链表排序
     * @param head
     * @return
     */
    private static ListNode sortList(ListNode head) {
        // 注意特判：为空||单个元素就不用排序了
        if(head == null || head.next == null) return head;

        // 1. 获取链表的中间节点，并划分链表
        ListNode t = getMid(head);
        ListNode hou = t.next;
        t.next = null;
        // 2. 递归排序
        ListNode left = sortList(head); // 这里是head
        ListNode right = sortList(hou);

        // 3. 合并两个有序链表
        return merge(left, right);
    }

    /**
     * 归并两个有序链表
     * @param list1
     * @param list2
     * @return
     */
    private static ListNode merge(ListNode list1, ListNode list2) {
        ListNode dummy = new ListNode(-1);
        ListNode cur = dummy;
        while (list1 != null && list2 != null){
            if(list1.val <= list2.val){
                cur.next = list1;
                list1 = list1.next;
            }else {
                cur.next = list2;
                list2 = list2.next;
            }
            cur = cur.next;
        }
        // 扫尾
        if(list1 != null) cur.next = list1;
        if(list2 != null) cur.next = list2;

        return dummy.next;
    }

    private static ListNode getMid(ListNode head) {
        ListNode fast = head, slow = head;
        while (fast.next != null && fast.next.next != null){
            fast = fast.next.next;
            slow = slow.next;
        }
        return slow;
    }
}
